package com.cyp.livelog.web;

import com.cyp.livelog.bean.Article;
import com.cyp.livelog.bean.ArticleClass;
import com.cyp.livelog.bean.User;
import com.cyp.livelog.utils.DbUtils;
import com.mysql.jdbc.StringUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 日月星辰
 * @date 2020/12/15 20:25
 * @description
 */
@WebServlet("/user")
public class UserAction extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String action = req.getParameter("a");
    if (StringUtils.isNullOrEmpty(action)) {
      index(req, resp);
    } else if (action.equals("write")) {
      toWrite(req, resp);
    } else if (action.equals("addClass")) {
      addClass(req, resp);
    } else if (action.equals("articleClassDelete")) {
      articleClassDelete(req, resp);
    } else if (action.equals("articleClassUpdate")) {
      articleClassUpdate(req, resp);
    } else if (action.equals("updatePassword")) {
      req.getRequestDispatcher("/WEB-INF/user/updatePassword.jsp").forward(req, resp);
    }
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String action = req.getParameter("a");
    if (StringUtils.isNullOrEmpty(action)) {
      PrintWriter writer = resp.getWriter();
      resp.setCharacterEncoding("UTF-8");
      resp.setHeader("Content-type", "text/html;charset=UTF-8");
      writer.write("<script>alert('参数有误！')</script>");
    } else if (action.equals("write")) {
      write(req, resp);
    } else if (action.equals("articleClassAdd")) {
      articleClassAdd(req, resp);
    } else if (action.equals("articleClassUpdatePost")) {
      articleClassUpdatePost(req, resp);
    } else if (action.equals("updatePassword")) {
      updatePassword(req, resp);
    }
  }

  private void updatePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String password = req.getParameter("password");
    User user = (User) req.getSession().getAttribute("user");
    DbUtils.update("update user set password=? where username=？", password, user.getUsername());
    req.setAttribute("message", "密码修改成功！");
    req.getRequestDispatcher("/success.jsp").forward(req, resp);
  }

  private void articleClassAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String name = req.getParameter("name");
    resp.setCharacterEncoding("utf-8");
    User user = (User) req.getSession().getAttribute("user");
    if (user.getUsername().equals("admin")) {
      ResultSet res = DbUtils.query("select count(*) from article_class where name=?", name);
      try {
        res.next();
        if (res.getInt(1) > 0) {
          resp.setHeader("Content-type", "text/html;charset=UTF-8");
          resp.getWriter().print("<script>alert('已经存在的名称！无法添加');window.history.go(-1)</script>");
          return;
        }
        DbUtils.update("insert into article_class(name,create_time) values(?,now())", name);
        req.setAttribute("message", "提交成功！");
        req.getRequestDispatcher("/success.jsp").forward(req, resp);
      } catch (SQLException e) {
        e.printStackTrace();
      }

    } else {
      req.setAttribute("message", "权限不足！");
      req.getRequestDispatcher("/fail.jsp").forward(req, resp);
    }
    return;
  }

  private void articleClassDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setCharacterEncoding("utf-8");
    resp.setHeader("Content-type", "text/html;charset=UTF-8");
    User user = (User) req.getSession().getAttribute("user");
    if (user.getUsername().equals("admin")) {
      String id = req.getParameter("id");
      ResultSet res = DbUtils.query("select count(*) from article where class_id=?", Integer.valueOf(id));
      try {
        res.next();
        int count = res.getInt(1);
        if (count != 0) {
          resp.getWriter().print("<script>alert('该目录下存在文章，禁止删除');window.history.go(-1)</script>");
          return;
        }
        DbUtils.update("delete from article_class where id=?", Integer.valueOf(id));
        req.setAttribute("message", "提交成功！");
        req.getRequestDispatcher("/success.jsp").forward(req, resp);
      } catch (SQLException e) {
      }
    } else {
      req.setAttribute("message", "权限不足！");
      req.getRequestDispatcher("/fail.jsp").forward(req, resp);
    }
  }

  private void articleClassUpdatePost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    User user = (User) req.getSession().getAttribute("user");
    if (user.getUsername().equals("admin")) {
      String id = req.getParameter("id");
      String name = req.getParameter("name");
      DbUtils.update("update article_class set name=?,update_time=now() where id=?", name, Integer.valueOf(id));
      req.setAttribute("message", "更新成功！");
      req.getRequestDispatcher("/success.jsp").forward(req, resp);
    } else {
      req.setAttribute("message", "权限不足！");
      req.getRequestDispatcher("/fail.jsp").forward(req, resp);
    }
  }

  private void articleClassUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    User user = (User) req.getSession().getAttribute("user");
    if (user.getUsername().equals("admin")) {
      Integer id = Integer.valueOf(req.getParameter("id"));
      ResultSet res = DbUtils.query("select id,name from article_class where id=?", id);
      try {
        res.next();
        req.setAttribute("articleClass", new ArticleClass(res.getInt("id"), res.getString("name")));
      } catch (Exception e) {
      }
      req.getRequestDispatcher("/WEB-INF/user/updateClass.jsp").forward(req, resp);
      return;
    } else {
      req.setAttribute("message", "权限不足！");
      req.getRequestDispatcher("/fail.jsp").forward(req, resp);
    }
  }

  private void addClass(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    User user = (User) req.getSession().getAttribute("user");
    if (user.getUsername().equals("admin")) {
      ResultSet res = DbUtils.query("select id,name,create_time as createTime,update_time as updateTime from article_class");
      try {
        List<ArticleClass> alist = new ArrayList<>();
        while (res.next()) {
          ArticleClass aClass = new ArticleClass();
          aClass.setId(res.getInt(1));
          aClass.setName(res.getString(2));
          aClass.setCreateTime(res.getDate(3));
          aClass.setUpdateTime(res.getDate(4));
          alist.add(aClass);
        }
        req.setAttribute("articleClass", alist);
      } catch (Exception e) {
      }
      req.getRequestDispatcher("/WEB-INF/user/addClass.jsp").forward(req, resp);
    } else {
      req.setAttribute("message", "权限不足！");
      req.getRequestDispatcher("/fail.jsp").forward(req, resp);
    }
  }

  private void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    User user = (User) req.getSession().getAttribute("user");
    try {
      //年文章数
      ResultSet year = DbUtils
          .query("select count(*) as year from article where username=? and YEAR(create_time)=YEAR(now())", user.getUsername());
      int yearCount = 0;
      if (year.next()) {
        yearCount = year.getInt(1);
      }
      req.setAttribute("yearCount", yearCount);
      //本月文章数
      ResultSet month = DbUtils
          .query("SELECT count(*) FROM article WHERE DATE_FORMAT( create_time, '%Y%m' )=DATE_FORMAT( CURDATE( ), '%Y%m' )"
              + " and username=?", user.getUsername());
      int monthCount = 0;
      if (month.next()) {
        monthCount = month.getInt(1);
      }
      req.setAttribute("monthCount", monthCount);
      //获取最新的文章
      ResultSet articles = DbUtils.query("select id,title,create_time from article where username=? order by id desc", user.getUsername());
      List<Article> list = new ArrayList<>();
      while (articles.next()) {
        Article article = new Article();
        article.setId(articles.getInt(1));
        article.setTitle(articles.getString(2));
        article.setCreateTime(articles.getDate(3));
        list.add(article);
      }
      req.setAttribute("list", list);
    } catch (SQLException e) {
      e.printStackTrace();
    }
    req.getRequestDispatcher("/WEB-INF/user/index.jsp").forward(req, resp);
    return;
  }

  /**
   * 前往写文章页面
   */
  private void toWrite(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ResultSet res = DbUtils.query("select id,name from article_class");
    try {
      List<ArticleClass> alist = new ArrayList<>();
      while (res.next()) {
        alist.add(new ArticleClass(res.getInt("id"), res.getString("name")));
      }
      req.setAttribute("articleClass", alist);
    } catch (Exception e) {
    }
    req.getRequestDispatcher("/WEB-INF/user/write.jsp").forward(req, resp);
    return;
  }

  private void write(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String title = req.getParameter("title");
    String classId = req.getParameter("classId");
    String content = req.getParameter("content");
    User user = (User) req.getSession().getAttribute("user");
    DbUtils.update("insert into article(username,title,class_id,content,create_time) values(?,?,?,?,now())",
        user.getUsername(), title, classId, content);
    req.setAttribute("message", "提交成功！<a href=\"user?a=write\" style=\"color:red;\">再写一篇</a>");
    req.getRequestDispatcher("/success.jsp").forward(req, resp);
  }
}
